package cn.jsxz.controller;

import cn.jsxz.common.constants.Constants;
import cn.jsxz.common.utils.DateTimeUtil.DateUtil;
import cn.jsxz.common.utils.ResultUtil;
import cn.jsxz.dto.Result;
import cn.jsxz.entity.Admin;
import cn.jsxz.service.AdminService;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 管理员ControllergetAdminList
 *
 * @author zy
 * @ClassName: AdminController
 * @Description: TODO
 */
@RestController
@RequestMapping("/admin/")
public class AdminController {

    @Autowired
    private AdminService adminService;

    /**
     * @auther: Zy
     * @method login
     * 功能描述: 管理员登录
     * @params: [username, password, session]
     * @return: * @return : com.alibaba.fastjson.JSONObject
     * @date: 2019-02-15 09:44:49
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public JSONObject login(@RequestParam(value = "username") String username, @RequestParam(value = "password") String password, HttpSession session) {
        Admin admin = adminService.getOne(new QueryWrapper<Admin>().eq("login_name", username)
                .eq("del_flag", 0).eq("forbidden_flag", 0), true);
        if (admin != null) {
            String userPwd = admin.getLoginPwd();
            if (userPwd.equals(SecureUtil.md5(password))) {
                session.setAttribute("user", admin);
                session.setAttribute("name", admin.getName());
                session.setAttribute("pwd", password);
                session.setAttribute("id", admin.getAdminId());
                // 记录登陆时间
                admin.setLoginTime(DateUtil.getNowTime());
                boolean b = adminService.saveOrUpdate(admin);
                if (b) {
                    return ResultUtil.resultJSON(Constants.HTTP_STATE_CODE.SUCCESS_200, Constants.HTTP_STATE_MASSAGE.SUCCESS_LOGIN_MSG, admin);
                } else {
                    return ResultUtil.resultJSON(400, "登录失败!", null);
                }
            }
            return ResultUtil.resultJSON(400, "登录名或者密码不正确!", null);
        }
        return ResultUtil.resultJSON(400, "用户不存在!", null);
    }

    /**
     * @auther: Zy
     * @method getAllUser
     * 功能描述: 查询用户总数
     * @params: []
     * @return: * @return : int
     * @date: 2019-02-15 09:46:47
     */
    @RequestMapping(value = "getAllUser", method = RequestMethod.GET)
    public int getAllUser() {
        List<Admin> admin = adminService.list(new QueryWrapper<Admin>().eq("del_flag", 0));
        return admin.size();
    }

    /**
     * @auther: Zy
     * @method getUserInfo
     * 功能描述: 查询用户上次登陆时间
     * @params: [session]
     * @return: * @return : com.alibaba.fastjson.JSONObject
     * @date: 2019-02-15 09:47:02
     */
    @RequestMapping(value = "getUserInfo", method = RequestMethod.GET)
    public JSONObject getUserInfo(HttpSession session) {
        JSONObject jsonObject = new JSONObject();
        Admin admin = (Admin) session.getAttribute("user");
        jsonObject = (JSONObject) JSONObject.toJSON(admin);
        return jsonObject;
    }

    /**
     * @auther: Zy
     * @method changePwd
     * 功能描述: 修改管理员密码
     * @params: [oldPwd, newPwd, session]
     * @return: * @return : cn.jsxz.dto.Result
     * @date: 2019-02-15 09:47:14
     */
    @RequestMapping(value = "changePwd", method = RequestMethod.POST)
    public Result changePwd(@RequestParam(value = "oldPwd") String oldPwd, @RequestParam(value = "newPwd") String newPwd, HttpSession session) {
        Admin admin = adminService.getById(session.getAttribute("id").toString());
        if (null != admin) {
            String pwd = admin.getLoginPwd();
            if (pwd.equals(SecureUtil.md5(oldPwd))) {
                admin.setLoginPwd(SecureUtil.md5(newPwd));
                boolean b = adminService.updateById(admin);
                if (b) {
                    return ResultUtil.success();
                }
            } else {
                return ResultUtil.error("原密码输入有误！");
            }
        }
        return ResultUtil.error("该用户不存在！");
    }


    /**
     * @auther: Zy
     * @method adminAdd
     * 功能描述: 根据身份标识新增管理员
     * @params: [loginName, userPhoto, loginPwd, adminPhone, adminName, request]
     * @return: * @return : cn.jsxz.dto.Result
     * @date: 2019-02-15 09:47:43
     */
    @RequestMapping(value = "adminAdd", method = RequestMethod.POST)
    public Result adminAdd(@RequestParam(value = "loginName") String loginName, @RequestParam(value = "userPhoto") String userPhoto,
                           @RequestParam(value = "loginPwd") String loginPwd, @RequestParam(value = "adminPhone") String adminPhone,
                           @RequestParam(value = "adminName") String adminName) {
        Admin adm = adminService.getOne(new QueryWrapper<Admin>().eq("login_name", loginName).eq("del_flag", 0).eq("admin_leve", 2));
        if (adm != null) {
            return ResultUtil.error("该登录名已经存在");
        }
        Admin admin = new Admin();
        admin.setAdminId(RandomUtil.simpleUUID());
        admin.setLoginName(loginName);
        admin.setName(adminName);
        admin.setLoginPwd(SecureUtil.md5(loginPwd));
        admin.setPhoto(userPhoto);
        admin.setPhone(adminPhone);
        admin.setDelFlag(0);
        admin.setAdminLeve(2);
        admin.setForbiddenFlag(0);
        admin.setCreateTime(DateUtil.getNowTime());
        admin.setUpdateTime(DateUtil.getNowTime());
        boolean insert = adminService.save(admin);
        if (insert) {
            return ResultUtil.success();
        } else {
            return ResultUtil.error("新增失败");
        }
    }

    /**
     * @auther: Zy
     * @method adminUpdate
     * 功能描述: 编辑管理员
     * @params: [adminId, userPhoto, loginName, loginPwd, adminPhone, adminName, request]
     * @return: * @return : cn.jsxz.dto.Result
     * @date: 2019-02-15 09:48:05
     */
    @RequestMapping(value = "adminUpdate", method = RequestMethod.POST)
    public Result adminUpdate(@RequestParam(value = "adminId") String adminId, @RequestParam(value = "userPhoto") String userPhoto,
                              @RequestParam(value = "loginName") String loginName, @RequestParam(value = "loginPwd") String loginPwd,
                              @RequestParam(value = "adminPhone") String adminPhone, @RequestParam(value = "adminName") String adminName) {
        // 判断登录名是否已经存在
        Admin a = adminService.getOne(new QueryWrapper<Admin>().eq("login_name", loginName).eq("del_flag", 0).eq("forbidden_flag", 0));
        if (a != null && !a.getAdminId().equals(adminId)) {
            return ResultUtil.error("该登录名已经存在");
        }
        Admin admin = adminService.getById(adminId);
        if (null != admin) {
            admin.setLoginName(loginName);
            admin.setName(adminName);
            if (loginPwd != null && loginPwd != "") {
                admin.setLoginPwd(SecureUtil.md5(loginPwd));
            }
            admin.setPhone(adminPhone);
            admin.setPhoto(userPhoto);
            boolean update = adminService.updateById(admin);
            if (update) {
                return ResultUtil.success();
            } else {
                return ResultUtil.error("编辑失败");
            }
        } else {
            return ResultUtil.error("编辑失败");
        }
    }

    /**
     * @auther: Zy
     * @method toDelAdmin
     * 功能描述: 删除管理员
     * @params: [request]
     * @return: * @return : cn.jsxz.dto.Result
     * @date: 2019-02-15 09:48:26
     */
    @RequestMapping(value = "toDelAdmin", method = RequestMethod.POST)
    public Result toDelAdmin(HttpServletRequest request) {
        String adminId = request.getParameter("adminId");
        Admin admin = adminService.getById(adminId);
        if (admin.getAdminLeve() == 1) {
            return ResultUtil.error("超级管理员不允许删除");
        }
        admin.setDelFlag(1);
        System.out.println("id:" + adminId);
        boolean update = adminService.updateById(admin);
        if (update) {
            return ResultUtil.success();
        } else {
            return ResultUtil.error("删除失败");
        }
    }

    /**
     * @auther: Zy
     * @method adminReset
     * 功能描述: 重置管理员密码
     * @params: [request]
     * @return: * @return : cn.jsxz.dto.Result
     * @date: 2019-02-15 09:48:39
     */
    @RequestMapping(value = "adminReset", method = RequestMethod.POST)
    public Result adminReset(HttpServletRequest request) {
        String adminId = request.getParameter("adminId");
        Admin admin = adminService.getById(adminId);
        if (admin != null) {
            admin.setLoginPwd(SecureUtil.md5("123456"));
            admin.setUpdateTime(DateUtil.getNowTime());
        }
        boolean update = adminService.updateById(admin);
        if (update) {
            return ResultUtil.success();
        } else {
            return ResultUtil.error("删除失败");
        }
    }

    /**
     * @auther: Zy
     * @method getAdminList
     * 功能描述: 获取管理员列表
     * @params: [page, limit, adminName, request]
     * @return: * @return : cn.jsxz.dto.Result
     * @date: 2019-02-15 09:48:51
     */
    @RequestMapping(value = "getAdminList", method = RequestMethod.POST)
    public JSONObject getAdminList(@RequestParam(value = "page") Integer page, @RequestParam(value = "limit") Integer limit,
                                   @RequestParam(value = "adminName", required = false) String adminName) {
        IPage<Admin> pageMap = new Page<>();
        pageMap.setSize(limit);
        pageMap.setCurrent(page);
        QueryWrapper qw = new QueryWrapper();
        qw.eq("del_flag", 0);
        qw.orderByDesc("admin_leve");
        qw.orderByDesc("create_time");
        if (StrUtil.isNotEmpty(adminName)) {
            qw.like("name", adminName);
        }
        IPage<Admin> pageObject = adminService.page(pageMap);
        return ResultUtil.resultPage(pageObject.getTotal(), pageObject.getRecords());
    }
}
